<?php
/**
 * Created by PhpStorm.
 * User: qinlu
 * Date: 2018/7/19
 * Time: 16:14
 */
namespace Admin\Controller;

//店铺管理控制器
use Shop\Controller\WxpayController;
use Think\AjaxPage;

class ShopController extends BaseController {

    //店铺申请管理列表
    public function shop_apply_list(){
        //定义一个当前页
        $p=1;
        //定义一个每页显示条数
        $page_size=5;
        $off_size=($p-1)*$page_size;
        $where="shop_status !=2 and isvalid=1";
        $shop_data_count = M('shop')->where($where)->count();
        $total_page=ceil($shop_data_count/$page_size);
        //定义上一页
        $last=$p-1<1?1:$p-1;
        //定义下一页
        $next=$p+1>$total_page?$total_page:$p+1;

        //获取店铺申请列表
        $shop_data = M('shop')->where($where)->limit($off_size,$page_size)->select();
        if(!$shop_data){
            $this->assign('shop_data',[]);
            $this->display();
            return false;
        }
        $this->assign('shop_data',$shop_data);
        $this->assign('last',$last);
        $this->assign('next',$next);
        $this->assign('total_page',$total_page);
        $this->assign('p',$p);
        $this->display();
    }
    //修改店铺信息
    public function update_shop(){
        $id=I('id');
        // var_dump($id);die;
        
        if( $this->shop_info )
        {
            $id = $this->shop_info['shop_id'];
        }
       
        $where = [
            'shop_status' => 2,
            'isvalid' => 1,
            'id' => $id
        ];
         
        $shop_data= M('shop')->where($where)->fetchSql(0)->find();
        $ShopImages = M("ShopImages")->where("shop_id=$id")->fetchSql(0)->select();
        // var_dump($shop_data);die;
        $this->assign('ShopImages', $ShopImages);  // 商品相册
        $this->assign('shop_data',$shop_data);
        $this->display();
    }
    //店铺类型搜索
    public function shop_apply_list_search(){
        //通过店铺类型搜索条件
        $shop_type = I('shop_type');
        $shop_name = I('shop_name');
        $p = I('p',1);
        $where="shop_status !=2 and isvalid=1";
        if($shop_type){
            $where.=" and shop_type=".$shop_type;
        }
        if(!empty($shop_name)){
            $where.=" and shop_name like '%$shop_name%'";
        }
        //定义一个每页显示条数
        $page_size=5;
        $off_size=($p-1)*$page_size;
        $shop_data_count = M('shop')->where($where)->count();

        $total_page=ceil($shop_data_count/$page_size);

        //定义上一页
        $last=$p-1<1?1:$p-1;
        //定义下一页
        $next=$p+1>$total_page?$total_page:$p+1;

        //获取店铺申请列表
        $shop_data = M('shop')->where($where)->limit($off_size,$page_size)->select();

        if(!$shop_data){
            $this->shop_error('没有搜索到你要找的店铺');
        }
//        //获取店铺类型
//        $shop_type_id = array_column($shop_data, 'shop_type');
//        $shop_type_id_str=trim(implode(',',$shop_type_id),',');
//
//        $shop__type_data = M('shop_type')->where("id in($shop_type_id_str)")->select();
//        if(!$shop__type_data){
//            $this->shop_error('没有符合你要找的店铺类型');
//        }
//        foreach($shop_data as $k=>$v){
//            foreach($shop__type_data as $key=>$val){
//                if($v['shop_type'] == $val['id']){
//                    $shop_data[$k]['shop_type_name']=$val['shop_type_name'];
//                }else{
//                    $shop_data[$k]['shop_type_name']='';
//                }
//            }
//        }
        $this->shop_success('成功',['last'=>$last,'next'=>$next,'total_page'=>$total_page,'shop_data'=>$shop_data,'p'=>$p]);
    }
    //获取店铺类型
    public function get_shop_type(){
        $shop__type_data = M('shop_type')->where("isvalid=1")->select();
        return $shop__type_data;
    }
    //修改店铺状态
    public function update_shop_status(){
        $id = I('id');
        $shop = M('shop')
            ->field('id,shop_name,user_id,city_name,area_name,shop_address_street,shop_status,
            shop_tel,longitude,latitude, shop_user,')
            ->where(['id' => $id])
            ->find();

        if(!$shop)
        return  $this->shop_error('店铺不存在');

        $shop_status = I('shop_status');
        if( (int)$shop['shop_status'] === (int)$shop_status )
        {
            return $this->shop_success('操作成功');
        }
        
        M()->startTrans();

        if($shop_status == 2){
            //注册dada门店
            $origin_shop_id = 'xmtdd_'.date('ymd').'_'.$id;
            $dd_shop_info['station_name'] = $shop['shop_name'];
            $dd_shop_info['business'] = 13;
            $dd_shop_info['city_name'] = $shop['city_name'] ?$shop['city_name'] : '北京市';
            $dd_shop_info['area_name'] = $shop['area_name']?$shop['area_name'] : '东城区';
            $dd_shop_info['station_address'] = $shop['shop_address_street'] ? $shop['shop_address_street'] : '区驻地';
            $dd_shop_info['lng'] = $shop['longitude'];
            $dd_shop_info['lat'] = $shop['latitude'];
            $dd_shop_info['contact_name'] = $shop['shop_user'];
            $dd_shop_info['phone'] = $shop['shop_tel'];
            $dd_shop_info['origin_shop_id'] = $origin_shop_id;
            $shopList[] = $dd_shop_info;

            $shopAddApi['url'] = "/api/shop/add";
            $shopAddApi['businessParams'] = json_encode($shopList);

            $app_key = tpCache('shopping.dd_app_key');
            $app_secret = tpCache('shopping.dd_app_secret');
            $source_id = tpCache('shopping.dd_source_id');
            $is_test_dada= tpCache('shopping.dd_is_test');


            $config['app_key'] = $app_key;
            $config['app_secret'] = $app_secret;
            $config['v'] = '1.0';
            $config['format'] = 'json';
            $config['source_id'] = $is_test_dada == 1 ? '73753' : $source_id;
            $config['host'] = $is_test_dada == 1 ?  'http://newopen.qa.imdada.cn' : "https://newopen.imdada.cn";

            $dada_client = new DadaRequestClient($config, $shopAddApi);
            $resp = $dada_client->makeRequest();
            $resp = object_array($resp);
            if($resp['status'] == 'success'){
                $update_shop['origin_shop_id'] = $origin_shop_id;
            }else{
                return $this->shop_error('门店注册失败，请重新尝试');
            }
        }
        $update_shop['shop_status'] = $shop_status;
        $res=M('shop')->where(['id' => $id])->save($update_shop);
        
        if($res){
            if( $shop_status == 2 )
            {
                // 审核通过类的
                $shop_admin = M('admin')->where([
                    'user_id' => $shop['user_id']
                ])->find();

                if( !$shop_admin )
                {
                    $data = M('users')->field('mobile,email,password')->where([
                        'user_id' => $shop['user_id']
                    ])->find();

                    if( empty($data['mobile']) && empty($shop['shop_tel']) )
                    {
                        M()->rollback();
                        return $this->shop_error('未设置有效联系电话');
                    }

                    $admin['user_name'] = !empty($data['mobile']) ? $data['mobile'] : $shop['shop_tel'];
                    $admin['email'] = !empty($data['email']) ? $data['email'] : '' ;
                    $admin['password'] = encrypt(123456);
                    $admin['role_id'] = 8;
                    $admin['add_time'] = time();
                    $admin['user_id'] = $shop['user_id'];
                    $admin_res = M('admin')->add($admin);

                    if( !$admin_res )
                    {
                        M()->rollback();
                        return $this->shop_error('创建管理账户失败，请重新尝试');
                    }
                    $sign = '[鲜美特]';
                    $content = $sign."您的后台登录账号是".$admin['user_name']."初始密码是123456,请尽快修改！";
                    sendMessageRequest($data['mobile'],$content);

                }
            }
            M()->commit();
            $this->shop_success('操作成功');
        }else {
            $this->shop_error('操作失败');
        }
    }
    public function shop_del(){
        $id = I('id');
        $res=M('shop')->where("id = ".$id)->save(array('isvalid'=>0));
        if($res){
            $this->shop_success('删除成功');
        }else {
            $this->shop_error('删除失败');
        }
    }
    
    //店铺列表页面
    public function shop_list(){
        //定义一个当前页
        $p=1;
        //定义一个每页显示条数
        $page_size=5;
        $off_size=($p-1)*$page_size;
        $where="shop_status =2 and isvalid=1";
        $shop_data_count = M('shop')->where($where)->count();
        $total_page=ceil($shop_data_count/$page_size);
        //定义上一页
        $last=$p-1<1?1:$p-1;
        //定义下一页
        $next=$p+1>$total_page?$total_page:$p+1;

        //获取店铺申请列表
        $shop_data = M('shop')->where($where)->limit($off_size,$page_size)->select();
        if(!$shop_data){
            $this->assign('shop_data',[]);
            $this->display();
            return false;
        }
        //获取店铺类型
        $shop_type_id = array_column($shop_data, 'shop_type');
        $shop_tids = [];
        foreach($shop_type_id as $v)
        {
            if(!empty($v))
                $shop_tids[] = $v;
        }
        $shop_type_id_str=implode(',',$shop_tids);
        $where = [];
        if($shop_type_id_str!='')
        {
            $where = "id in({$shop_type_id_str})";
        }
        $shop__type_data = M('shop_type')->where($where)->fetchSql(0)->select();
        if(!$shop__type_data){
            $this->assign('shop_type_data',[]);
            $this->display();
            return false;
        }

        foreach($shop_data as $k=>$v){
            foreach($shop__type_data as $key=>$val){
                if($v['shop_type'] == $val['id']){
                    $shop_data[$k]['shop_type_name']=$val['shop_type_name'];
                }else{
                    $shop_data[$k]['shop_type_name']='';
                }
            }
        }
        //获取店铺类型
        $shop_type_data=$this->get_shop_type();
        $this->assign('shop_type_data',$shop_type_data);
        $this->assign('shop_data',$shop_data);
        $this->assign('last',$last);
        $this->assign('next',$next);
        $this->assign('total_page',$total_page);
        $this->assign('p',$p);
        $this->display();
    }
    //店铺类型搜索
    public function shop_list_search(){
        //通过店铺类型搜索条件
        $shop_type = I('shop_type');
        $shop_name = I('shop_name');
        $p = I('p',1);
        $where="shop_status =2 and isvalid=1";
        if($shop_type){
            $where.=" and shop_type=".$shop_type;
        }
        if(!empty($shop_name)){
            $where.=" and shop_name like '%$shop_name%'";
        }
        //定义一个每页显示条数
        $page_size=5;
        $off_size=($p-1)*$page_size;
        $shop_data_count = M('shop')->where($where)->count();

        $total_page=ceil($shop_data_count/$page_size);
        //定义上一页
        $last=$p-1<1?1:$p-1;
        //定义下一页
        $next=$p+1>$total_page?$total_page:$p+1;
        //获取店铺申请列表
        $shop_data = M('shop')->where($where)->limit($off_size,$page_size)->fetchSql(0)->select();

        if(!$shop_data){
            $this->shop_error('没有搜索到你要找的店铺');
        }
        $this->shop_success('成功',['last'=>$last,'next'=>$next,'total_page'=>$total_page,'shop_data'=>$shop_data,'p'=>$p]);
    }

    //店铺评价列表
    public function shop_comment_list(){
        $data=$this->page('shop_comment');
        //获取店铺类型
        $shop_id = array_column($data['data'], 'shop_id');
        $shop_id=array_unique($shop_id);
        $shop_id_str=implode(',',$shop_id);
        $shop__comment_data = M('shop')->field('id,shop_name')->where("id in($shop_id_str)")->select();
        if(!$shop__comment_data){
            $this->shop_error('没有找到您要的评价的店铺');
        }

        foreach($data['data'] as $k=>$v){
            foreach($shop__comment_data as $key=>$val){
                if($v['shop_id'] == $val['id']){
                    $data['data'][$k]['shop_name']=$val['shop_name'];
                }
            }
        }
        $this->assign('data',$data);
        $this->display();

    }

    //封装一个分页
//    $p:当前页
//    $table:表名
//    $page_size:每页显示条数
//    $where:条件
    public function page($table,$where='',$p=1,$page_size=5){
        //算出便宜啦
        $off_size=($p-1)*$page_size;
        if($where){
            $count = M($table)->where($where)->count();
        }else{
            $count = M($table)->count();
        }
        //算出总页数
        $total_page=ceil($count/$page_size);
        //定义上一页
        $last=$p-1<1?1:$p-1;
        //定义下一页
        $next=$p+1>$total_page?$total_page:$p+1;
        if($where){
            $data = M($table)->where($where)->limit($off_size,$page_size)->select();
        }else{
            $data = M($table)->limit($off_size,$page_size)->select();
        }
        return ['p'=>$p,'last'=>$last,'next'=>$next,'total_page'=>$total_page,'data'=>$data];
    }

    public function shop_comment_list_search(){
        $comment_type = I('comment_type');
        $shop_name = I('shop_name');
        $p = I('p',1);
        $where='1=1';

        if($comment_type){
            $where .= " and ln_shop_comment.isvalid=$comment_type";
        }
        if($shop_name){
            $where .= " and shop_name like '%$shop_name%'";
        }
        $page_size=5;
        $off_size=($p-1)*$page_size;
        $shop =M('shop_comment');
        $count = $shop -> join('ln_shop ON ln_shop_comment.shop_id = ln_shop.id')
            ->where($where)
            ->limit($off_size,$page_size)
            -> count();
        //算出总页数
        $total_page=ceil($count/$page_size);
        //定义上一页
        $last=$p-1<1?1:$p-1;
        //定义下一页
        $next=$p+1>$total_page?$total_page:$p+1;

        $data = $shop -> join('ln_shop ON ln_shop_comment.shop_id = ln_shop.id')
            ->limit($off_size,$page_size)
            ->where($where)
            -> select();
        $this->shop_success('成功',['data'=>$data,'next'=>$next,'last'=>$last,'p'=>$p,'total_page'=>$total_page]);
    }
    //修改评论是否显示
    public function update_comment_status(){
        //接值
        $id=I('id');
        $comment_status=I('comment_status');

        $res=M('shop_comment')->where("id=$id")->save(array('isvalid'=>$comment_status));
        if($res){
            $this->shop_success('修改成功');
        }else{
            $this->shop_error('修改失败');
        }
    }

    //店铺类型页面
    public function shop_type(){
        $data=M('shop_type')->where('isvalid=1')->select();
        $this->assign('data',$data);
        $this->display();
    }
    //添加或修改店铺类型
    public function add_shop_type(){
        if(IS_POST){
            $shop_type['shop_type_name']=I('shop_type_name');
            $shop_type['is_show']=I('is_show');
            $shop_type['bond_price']=I('bond_price');
            $shop_type['sort']=I('sort');
            $shop_type['create_time']=date('Y-m-d H:i:s',time());
            $res=M('shop_type')->add($shop_type);
            if($res){
                $this->success('添加成功',U('Admin/Shop/shop_type'));
            }else{
                $this->error('添加失败');
            }
        }else{
            $this->display();
        }

    }
    //删除数据类型
    public function shop_type_del(){
        $id = I('id');
        $res=M('shop_type')->where("id = ".$id)->save(array('isvalid'=>0));
        if($res){
            $this->success('删除成功');
        }else {
            $this->error('删除失败');
        }
    }
    //修改店铺类型
    public function update_shop_type(){
        $id = I('id');
        $data=M('shop_type')->where("isvalid=1 and id=$id")->find();
        $this->assign('data',$data);
        $this->display();
    }


    //添加或修改店铺类型
    public function shop_type_update(){
        if(IS_POST){
            $shop_type['shop_type_name']=I('shop_type_name');
            $shop_type['id']=I('ids');
            $shop_type['is_show']=I('is_show');
            $shop_type['bond_price']=I('bond_price');
            $shop_type['sort']=I('sort');
            $shop_type['update_time']=date('Y-m-d H:i:s',time());
            $res=M('shop_type')->save($shop_type);
            if($res){
                $this->success('修改成功',U('Admin/Shop/shop_type'));
            }else{
                $this->error('修改失败');
            }
        }else{
            $this->display();
        }

    }
    //修改店铺信息
    public function shop_update()
    {
        $shop['shop_name']=I('shop_name');
        $id=I('ids');

        if( $this->shop_info )
        {
            if( $this->shop_info['shop_id'] != $id )
            {
                return $this->error("非法操作");
            }
        }

        $rec_shop = M('shop')->where([
            'shop_name' => $shop['shop_name']
        ])->find();

        if( $rec_shop && $rec_shop['id'] != $id )
        {
            return $this->error("店铺不能重名");
        }

        $shop['shop_user']=I('shop_user');
        $shop['shop_tel']=I('shop_tel');
        $shop['shop_intro']=I('shop_intro');
        $shop['shop_address_city']=I('shop_address_city');
        $shop['shop_address_street']=I('shop_address_street');
        $shop['license_name']=I('license_name');
        $shop['license_address_city']=I('license_address_city');
        $shop['license_address_street']=I('license_address_street');
        $shop['fee_freepost']=I('fee_freepost');
        $shop['default_postfee']=I('default_postfee');
        $shop['first_weight']=I('first_weight');
        $shop['second_weight']=I('second_weight');
        $shop['add_postfee']=I('add_postfee');
        if($_FILES['license_img']['name']){
            $shop['license_img']=$this->upload('license_img');
        }
        if($_FILES['shop_head_img']['name']){
            $shop['shop_head_img']=$this->upload('shop_head_img');
        }
        if($_FILES['shop_bei_img']['name']){
            $shop['shop_bei_img']=$this->upload('shop_bei_img');
        }  
        // $shop_img_info = M('shop_images')->where("shop_id=$id")->select();
        

        // if($shop_img_info){
        //     // $where['status'] = 0;
        //     $update = M('shop_images')->where("shop_id=$id")->save($where);
        // }else{
        //     $this->saves($id);
        // }
        $this->saves($id);
        $res=M('shop')->where([
            "id" => $id
        ])->save($shop);
        if($res!==false){

            if( $this->shop_info )
            {
                $url =  U('Admin/Shop/update_shop');
            }else{
                $url = U('Admin/Shop/shop_list');
            }
            \Common\Logic\FeeLogic::rmPostFeeCache($id);
            $this->success('修改成功',$url);
        }else{
            $this->error('修改失败');
        }
    }

    public function saves($id){
         // 添加图片
        if( empty($_POST['shop_images']) ) return true;
        $shop_img_info = M('shop_images')->where("shop_id=$id")->select();

        $shopImagesArr = $shop_img_info ? array_column($shop_img_info, 'image_url') : [];

        foreach($_POST['shop_images'] as $key => $val)
        {
            if($val == null)  continue;                                  
            if(!in_array($val, $shopImagesArr))
            {                 
                $shop = array(
                    'shop_id' => $id,
                    'image_url' => $val,
                    'status' => 1
                );
                $res =  M("ShopImages")->where("id=$id")->data($shop)->add();; // 实例化User对象                     
            }
        }
        $del_ids = [];
        foreach( $shop_img_info as $k => $v )
        {
            if(!in_array($v['image_url'], $_POST['shop_images']))
            { 
                $del_ids[] = $v['img_id'];
            }
        }

        if( !empty($del_ids) )
        {
            M("ShopImages")->where([
                "img_id" => ['IN', $del_ids]
            ])->delete();
        }
        M('shop_images')->where("shop_id=$id")->save([
            "status" => 1
        ]);
        return $res;
    }


    /* 奖品图片上传 */
    public function upload($name,$flag = true){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     UPLOAD_PATH.'shop/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            if($flag){
                $this->error($upload->getError());
                exit;
            }else{
                return false;
            }
        }else{// 上传成功
            return $info[$name]['urlpath'];
        }
    }

    //店铺交易统计
    public function shop_transaction()
    {
        /*if ($this->shop_info)
        {
            $shop_info = M('shop as s')
            ->join('ln_order as o on o.shop_id=s.id')
            ->field('s.id,s.shop_name,s.shop_tel,sum(o.goods_price) goods_price')
            ->where([
                "o.order_status" => 4,
                "s.id" => $this->shop_info['shop_id']
            ])
            ->group('id')
            ->select(); 
        }else{*/
            $shop_info = M('shop as s')
            ->join('ln_order as o on o.shop_id=s.id')
            ->field('s.id,s.shop_name,s.shop_tel,sum(o.goods_price) goods_price')
            ->where('order_status in (2,4)')
            ->group('s.id')
            ->select();   
        //}
        $this->assign('shop_info',$shop_info);       
        $this->display();

    }


    /**
    *店铺装修
    */
    public function shop_fixture(){
        $this->display();

    }

    /**
     * 删除商品相册图
     */
    public function del_goods_images()
    {
        $path = I('filename','');
        M('shop_images')->where("image_url = '$path'")->delete();
    }



    //返回错误信息
    public function shop_error($message,$data=''){
        $error=[
            'message'=>$message,
            'result'=>'400',
            'data'=>$data
        ];
        exit(json_encode($error));
    }
    //返回成功
    public function shop_success($message,$data=''){
        $success=[
            'message'=>$message,
            'result'=>'200',
            'data'=>$data
        ];
        exit(json_encode($success));
    }

    public function shop_account_number(){
        $res = $list = array();
        $keywords = I('keywords', '', 'trim');

        $model = D('admin');
        $where['role_id'] = 8;
        if($keywords){
            $where['user_name'] = array('like', '%'.$keywords.'%');
        }

        $count = $model->where($where)->count();
        $Page = new AjaxPage($count, 10);
        $show = $Page->show();
        $order_str = "`admin_id` DESC";
        $res = $model->where($where)->order($order_str)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $shop_list = M('shop')->field('id, shop_name, shop_user, user_id')->select();
        $shop_list = convert_arr_key($shop_list, 'user_id');

        foreach ($res as $val){
            $val['add_time'] = date('Y-m-d H:i:s',$val['add_time']);
            $val['shop_name'] = $shop_list[$val['user_id']]['shop_name'];
            $val['shop_user'] = $shop_list[$val['user_id']]['shop_user'];
            $list[] = $val;
        }

        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->display();
    }

    /**
     * 提现申请记录
     */
    public function withdrawals()
    {
        $this->display();
    }

    public function ajaxwithdrawals(){
        $model = M("withdrawals_shop");
        $_GET = array_merge($_GET,$_POST);
        unset($_GET['create_time']);

        $status = I('withdraw.status');
        $shop_name = I('shop_name');
        $account_bank = I('account_bank');
        $account_name = I('account_name');
        $create_time = I('create_time');

        $create_time = $create_time  ? $create_time  : date('Y/m/d',strtotime('-1 year')).'-'.date('Y/m/d',strtotime('+1 day'));
        $create_time2 = explode('-',$create_time);
        $where = " withdraw.create_time >= '".strtotime($create_time2[0])."' and withdraw.create_time <= '".strtotime($create_time2[1])."' ";

        if($status === '0' || $status > 0)
            $where .= " and withdraw.status = $status ";
        $shop_name && $where .= " and shop.shop_name like '%$shop_name%";
        $account_bank && $where .= " and withdraw.account_bank like '%$account_bank%' ";
        $account_name && $where .= " and withdraw.account_name like '%$account_name%' ";

        $count = $model->alias('withdraw')
            ->join('ln_shop shop on withdraw.shop_id = shop.id', 'left')
            ->where($where)
            ->count();
        $Page  = new AjaxPage($count,16);
        $list = $model->alias('withdraw')
            ->field('withdraw.* , shop.shop_name, shop.id as shop_id')
            ->join('ln_shop shop on withdraw.shop_id = shop.id', 'left')
            ->where($where)->order("withdraw.`id` desc")->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign('create_time',$create_time);
        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
    }

    /**
     * 修改编辑 申请提现
     */
    public  function editWithdrawals(){
        $id = I('id');
        $model = M("withdrawals_shop");
        $withdrawals = $model->find($id);
        if(!$withdrawals){
            $this->error("提现信息有误");
            exit;
        }
        $shop = M('shop')->where("id = {$withdrawals[shop_id]}")->find();

        if(IS_POST)
        {
            $model->create();

            // 如果是已经给用户转账 则生成转账流水记录
            if($withdrawals['status'] == 0){
                if($model->status == 1) {
                    $wxPay = new WxpayController();
                    $res = $wxPay->withdraw_pay($id);
                    if($res['status'] != 1){
                        $this->error($res['msg']);
                        exit;
                    }

                    $is_success = accountLogShop($withdrawals['shop_id'], 0 - $withdrawals['money'], '提现', 0, 0,
                        0, 0, '');
                    if($is_success['is_success'] === false){
                        M()->rollback();
                        $this->returnInfo(0, '操作失败');
                    }

                    $remittance = array(
                        'shop_id' => $withdrawals['shop_id'],
                        'bank_name' => $withdrawals['bank_name'],
                        'account_bank' => $withdrawals['account_bank'],
                        'account_name' => $withdrawals['account_name'],
                        'change_money' => $withdrawals['money'],
                        'is_settlement' => 1,
                        'add_time' => time(),
                        'admin_id' => session('admin_id'),
                        'withdrawals_id' => $withdrawals['id'],
                        'remark'=>$model->remark,
                    );
                    M('shop_settlement_log')->add($remittance);
                }
            }

            $model->save();
            $this->success("操作成功!");
            exit;
        }



        //if($user['nickname'])
            $withdrawals['shop_name'] = $shop['shop_name'];
        //elseif($user['email'])
            //$withdrawals['user_name'] = $user['email'];
        //elseif($user['mobile'])
            //$withdrawals['user_name'] = $user['mobile'];

        $this->assign('user',$shop);
        $this->assign('data',$withdrawals);
        $this->display();
    }

    public function capital(){
        $begin = date('Y/m/d',(time()-30*60*60*24));//30天前
        $end = date('Y/m/d',strtotime('+1 days'));
        $this->assign('create_time',$begin.'-'.$end);
        $this->display();
    }

    public function ajaxcapital(){
        $shop_name = I('shop_name');
        $create_time = I('create_time');

        $create_time = $create_time  ? $create_time  : date('Y/m/d',strtotime('-1 year')).'-'.date('Y/m/d',strtotime('+1 day'));
        $create_time2 = explode('-',$create_time);
        $where = " capital.create_time >= '".strtotime($create_time2[0])."' and capital.create_time <= '".strtotime($create_time2[1])."' ";

        $shop_name && $where .= " and shop.shop_name like '%$shop_name%'";
        $model = M("shop_capital_log");
        $count = $model->alias('capital')
            ->join('ln_shop shop on capital.shop_id = shop.id', 'left')
            ->join('ln_order ord on capital.order_id = ord.order_id', 'left')
            ->where($where)
            ->count();

        $Page  = new AjaxPage($count,16);
        $list = $model->alias('capital')
            ->field('capital.* , shop.shop_name, shop.id as shop_id, ord.order_sn, ord.order_amount')
            ->join('ln_shop shop on capital.shop_id = shop.id', 'left')
            ->join('ln_order ord on capital.order_id = ord.order_id', 'left')
            ->where($where)->order("capital.`id` desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        $show = $Page->show();
        $this->assign('show', $show);
        $this->assign('list', $list);
        $this->assign('create_time',$create_time2);
        $this->display();
    }
}